package com.example.control;

import com.example.domain.t_comment;
import com.example.domain.t_user;
import com.example.model.responseData.articleResponseData;
import com.example.service.IArticleService;
import com.example.service.ICommentService;


import com.example.service.IUserService;
import com.example.utils.myUtils;
import com.vdurmont.emoji.EmojiParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@RequestMapping("/comments")
public class CommentControl {

    private static final Logger logger= (Logger) LoggerFactory.getLogger(CommentControl.class);
    @Autowired
    private ICommentService comm;
    @Autowired
    private IArticleService iart;

    @Autowired
    private IUserService iuse;

    //发表评论
    @RequestMapping("/publish")
    @ResponseBody
    public articleResponseData publishComment(HttpServletRequest req,
            @RequestParam int aid,@RequestParam String text){
        //去除js
        text = myUtils.cleanXSS(text);
        text = EmojiParser.parseToAliases(text);

        //System.out.println(text);
        //获取当前用户
//       User user = (User) SecurityContextHolder.
//      getContext().getAuthentication().getPrincipal();
        t_user user = (t_user)req.getSession().getAttribute("loginUser");
        if(user==null){
            logger.error("发表评论失败,未登录用户");
            return articleResponseData.fail("未登录");
        }
        //封装评论信息
        //System.out.println(user);
        t_comment comment = new t_comment();
        comment.setArticle_id(aid); //从属的文章
        comment.setAuthor(user.getUsername()); //评论的作者
        comment.setContent(text);  //内容
        comment.setCreated(new Date()); //时间
        comment.setHits(0); //点赞数量
        comment.setIp(req.getRemoteAddr()); //评论的ip地址
        try{
            comm.insert(comment);
            logger.info("发表评论成功，对应文章ID："+aid+",内容:"+text.substring(0,5));
            return articleResponseData.ok();
        }catch (Exception e){
            logger.error("发表失败，对应文章id："+aid+",错误："+e.getMessage());
            e.printStackTrace();
            return articleResponseData.fail();
        }
    }

    //删除评论
    @RequestMapping("/delete/{c_id}")
    @ResponseBody
    public articleResponseData deleteComment(HttpServletRequest req,@PathVariable("c_id") Integer c_id){
        try{
            t_user user = (t_user)req.getSession().getAttribute("loginUser");
            t_comment comment = comm.get(c_id);
            Integer article_id = comment.getArticle_id();
            int user_id = iart.selectById(article_id).getUser_id();

            if(user==null || c_id == null ||(user_id!=user.getId() && !iuse.Isroot(user.getId()) && !comment.getAuthor().equals(user.getUsername()))){
                logger.error("删除评论失败");
                return articleResponseData.fail("");
            }
            comm.delete(c_id);
            logger.info(user.getUsername()+"删除"+c_id+"了一条评论 "+comment.getContent());
            return articleResponseData.ok();
        }catch (Exception e){
            logger.error("删除评论错误，错误信息："+e.getMessage());
            return articleResponseData.fail("");
        }

    }
}
